package com.jbit.dm_160.service.impl;

import com.jbit.dm_160.mapper.UserMapper;
import com.jbit.dm_160.model.dto.TokenDTO;
import com.jbit.dm_160.model.entity.User;
import com.jbit.dm_160.service.UserService;
import com.jbit.dm_160.utils.Constance;
import com.jbit.dm_160.utils.RedisUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisUtils redisUtils;
    @Override
    public Object[] getUserByPhone(String phone,String password) {

        User user = userMapper.getUserByPhone(phone);
        if (user != null && user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))){
            Object[] objects = new Object[2];
            objects[0] = user;
            //生成token,保存到redis中做持久保存,方便后期验证
            //保存到objects数组,传给前端正常使用
            String token = UUID.randomUUID().toString() + "_" + user.getId();
            long genTime = System.currentTimeMillis();//ms
            TokenDTO tokenDTO = new TokenDTO();
            tokenDTO.setToken(token);
            tokenDTO.setGenTime(genTime);
            tokenDTO.setExpTime(genTime + Constance.TOKEN_EXPIRE_TIME);
            redisUtils.set(token,user, Constance.TOKEN_EXPIRE_TIME);
            objects[1] = tokenDTO;
            return objects;
        }
        return null;
    }

    @Override
    public User getUserByToken(String token) {
        return (User) redisUtils.getObject(token,User.class);
    }
}
